<template>
  <a-form ref="form"
          :model="formState"
          :rules="formRules"
          autocomplete="off"
          class="form"
          layout="vertical"
          @finish="handleSmsCodeLogin">
    <a-form-item label="手机号" name="phoneNumber">
      <a-input v-model:value="formState.phoneNumber" placeholder="输入手机号" size="large">
        <template #prefix>
          <mobile-outlined style="color:rgba(0,0,0,.25)"/>
        </template>
      </a-input>
    </a-form-item>
    <a-form-item label="验证码" name="smsCode">
      <div class="flex gap-2">
        <div class="grow">
          <a-input ref="smsCodeInput" v-model:value="formState.smsCode" :maxlength="6" placeholder="输入验证码"
                   size="large">
            <template #prefix>
              <icon-font style="color:rgba(0,0,0,.25)" type="envelope"/>
            </template>
          </a-input>
        </div>
        <div>
          <a-button :disabled="countdown > 0"
                    :loading="sendSmsCodeLoading"
                    ghost
                    size="large"
                    type="primary"
                    @click="handleSendSmsCode">
            {{ sendSmsCodeButtonText }}
          </a-button>
        </div>
      </div>
    </a-form-item>
    <a-button :loading="smsCodeLoginLoading" block class="submit" html-type="submit" size="large" type="primary">
      {{ loginButtonText }}
    </a-button>
  </a-form>
</template>

<script setup>
import {MobileOutlined} from "@ant-design/icons-vue";

const props = defineProps(['loginButtonText', 'extraParams']);
const loginButtonText = computed(() => props.loginButtonText ?? '登录')

const form = ref(null);
const smsCodeInput = ref(null);

const formState = reactive({
  phoneNumber: '',
  smsCode: '',
});
const formRules = {
  phoneNumber: [
    {required: true, message: '请输入手机号'},
    {pattern: /^1\d{10}$/, message: '请输入正确的手机号'}
  ],
  smsCode: [
    {required: true, message: '请输入验证码'},
    {pattern: /^\d{6}$/, message: '请输入正确的验证码'}
  ]
};

const {isLoading: sendSmsCodeLoading, execute: sendSmsCode} = useApi({
  method: 'POST',
  url: '/login/sms-code/send',
  immediate: false
});
const sendSmsCodeButtonText = ref('发送验证码');
const countdown = ref(0);
const countdownTimer = ref(null);
const tick = () => {
  countdown.value--;
  if (countdown.value === 0) {
    clearInterval(countdownTimer.value);
    countdownTimer.value = null;
  }
};

watchEffect(() => {
  if (countdown.value > 0) {
    sendSmsCodeButtonText.value = `${countdown.value} 秒后可重发`;

    if (countdownTimer.value == null) {
      countdownTimer.value = setInterval(tick, 1000);
    }
  } else {
    sendSmsCodeButtonText.value = '发送验证码';
  }
});

const handleSendSmsCode = async () => {
  try {
    await form.value.validateFields('phoneNumber');
  } catch (e) {
    return;
  }
  try {
    const {nextTimeInSeconds} = await sendSmsCode({
      data: {
        phoneNumber: formState.phoneNumber
      }
    });
    countdown.value = nextTimeInSeconds;
    message.success('验证码已发送成功');
    smsCodeInput.value.focus();
  } catch (e) {
    const {nextTimeInSeconds} = e.response.data;
    countdown.value = nextTimeInSeconds;
  }
}

const {isLoading: smsCodeLoginLoading, execute: smsCodeLogin} = useApi({
  method: 'POST',
  url: '/login/sms-code',
  immediate: false
});
const router = useRouter();
const handleSmsCodeLogin = async () => {
  await smsCodeLogin({
    data: {
      ...formState,
      ...props.extraParams
    }
  });
  await router.push({
    path: '/'
  });
};
</script>
